package com.wenronghui.lab3.service;

import com.wenronghui.lab3.model.RegionStats;
import org.springframework.core.io.Resource;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.input.BOMInputStream;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
@EnableScheduling
public class FetchDataService {
    final static String FETCH_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    @Scheduled(fixedRate = 5000)
    public List<RegionStats> getData() throws IOException {

//        设置请求头部并请求数据：
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(FETCH_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/76.0"))
                .build();

//        实例化一个RequestEntity对象，再通过RestTemplate的exchange方法获取csv文件，文件的数据会封装到一个Resource对象中。
        ResponseEntity<Resource> resourseResponseEntity = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource resource = resourseResponseEntity.getBody();

//        通过Resource对象的getInputStream方法获取csv文件的输入流。
        final Reader reader = new InputStreamReader(new BOMInputStream(resource.getInputStream()), StandardCharsets.UTF_8);
        final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());


        List<RegionStats> regionStatsList = new ArrayList<>();
        try {
            for (final CSVRecord record : parser) {
                String state = record.get("Province/State");
                String country = record.get("Country/Region");
                String longi = record.get("Long");
                String lat = record.get("Lat");
                int latestTotalCases = Integer.parseInt(record.get(record.size() - 1));
                int diffFromPrevDay = record.size() > 5 ?
                        Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)) : latestTotalCases;

                RegionStats regionStats = new RegionStats();
                regionStats.setState(state);
                regionStats.setCountry(country);
                regionStats.setLongi(longi);
                regionStats.setLat(lat);
                regionStats.setLatestTotalCases(latestTotalCases);
                regionStats.setDiffFromPrevDay(diffFromPrevDay);
                regionStatsList.add(regionStats);
            }
        } finally {
            parser.close();
            reader.close();
        }

        return regionStatsList;
    }


}

